package controller;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Context;
import org.apache.catalina.Session;

//import model.InitialContext;
//import model.InternetAddress;
//import model.Message;
//import model.MimeMessage;
import model.Repository;
import model.UserRepository;
import myBeans.*;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	
	
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub      
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException, SQLException {
		Connection conn = (Connection) getServletContext().getAttribute("connection");
				
		HttpSession session = request.getSession(true);
		
		
		session.setAttribute("loginFlag", false);
		String userid = request.getParameter("userid");
		String password = request.getParameter("password");
		
		LoginInfo  LoginBean = new LoginInfo();
		LoginBean.setUserId(userid);
		LoginBean.setPassword(password);
		
		Repository repo = new Repository(conn);
		boolean IsLogin = repo.Login(LoginBean);
		
		if(IsLogin){
			UserInfo user = new UserRepository().GetUserInfo(userid);
			session.setAttribute("loginFlag", true);
			session.setAttribute("User", user);
			response.sendRedirect("TopView.jsp");
		}else{
			response.sendRedirect("Index.jsp?IsLogin=false");
		}
	}
	


}
